package go_grpc

import (
	"fmt"
	"gitee.com/crack007/go_config"
	"gitee.com/crack007/go_log"
	"google.golang.org/grpc"
	"net"
)

type Callable func(*grpc.Server)

type Grpc struct {
	GrpcConfig   *GrpcConfig
	GrpcServer   *grpc.Server
	registerList []Callable
}

func NewGrpc(serviceName string) *Grpc {
	return &Grpc{
		GrpcConfig: NewServiceConfig(serviceName),
	}
}

//    服务启动
func (g *Grpc) Bootstrap() error {
	go_config.Bootstrap()
	go_log.Bootstrap()
	address := fmt.Sprintf("%s:%d", g.GrpcConfig.Host, g.GrpcConfig.Port)
	server, err := net.Listen("tcp", address)
	if err != nil {
		go_log.Error("Grpc server failed to listen-> %s", err.Error())
		return err
	}
	g.GrpcServer = grpc.NewServer()
	if len(g.registerList) > 0 {
		// 注册监听服务
		for _, callable := range g.registerList {
			callable(g.GrpcServer)
		}
	}
	go_log.Warn("Grpc server listen-> %s", address)
	err = g.GrpcServer.Serve(server)
	if err != nil {
		go_log.Error("Grpc server failed to  bootstrap-> %s", err.Error())
		return err
	}
	return nil
}

func (g *Grpc) Shutdown() {
	if g.GrpcServer != nil {
		g.GrpcServer.GracefulStop()
	}
}

func (g *Grpc) RegisterService(callable Callable) {
	g.registerList = append(g.registerList, callable)
}
